#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
渐进式数据管理器测试运行器

使用方法:
    python run_tests.py              # 运行所有测试
    python run_tests.py --unit       # 只运行单元测试
    python run_tests.py --performance # 只运行性能测试
    python run_tests.py --quick      # 快速测试（跳过性能测试）
"""

import sys
import os
import argparse
import subprocess
import time
from datetime import datetime

def print_header(title):
    """打印测试标题"""
    print(f"\n{'='*60}")
    print(f" {title}")
    print(f"{'='*60}")

def print_section(title):
    """打印测试节标题"""
    print(f"\n{'-'*40}")
    print(f" {title}")
    print(f"{'-'*40}")

def run_unit_tests():
    """运行单元测试"""
    print_section("单元测试")
    
    try:
        # 直接运行测试文件
        test_file = os.path.join("test", "test_progressive_data_manager.py")
        if os.path.exists(test_file):
            print(f"运行 {test_file}...")
            result = subprocess.run([sys.executable, test_file], 
                                  capture_output=True, text=True, cwd=os.getcwd())
            
            if result.returncode == 0:
                print(result.stdout)
                return True
            else:
                print("❌ 单元测试失败:")
                print(result.stderr)
                return False
        else:
            print(f"❌ 测试文件不存在: {test_file}")
            return False
            
    except Exception as e:
        print(f"❌ 运行单元测试时发生错误: {e}")
        return False

def run_performance_tests():
    """运行性能测试"""
    print_section("性能测试")
    
    try:
        test_file = os.path.join("test", "test_performance.py")
        if os.path.exists(test_file):
            print(f"运行 {test_file}...")
            result = subprocess.run([sys.executable, test_file], 
                                  capture_output=True, text=True, cwd=os.getcwd())
            
            if result.returncode == 0:
                print(result.stdout)
                return True
            else:
                print("❌ 性能测试失败:")
                print(result.stderr)
                return False
        else:
            print(f"❌ 测试文件不存在: {test_file}")
            return False
            
    except Exception as e:
        print(f"❌ 运行性能测试时发生错误: {e}")
        return False

def check_dependencies():
    """检查测试依赖"""
    print_section("依赖检查")
    
    required_modules = ['psutil']
    missing_modules = []
    
    for module in required_modules:
        try:
            __import__(module)
            print(f"[OK] {module} 已安装")
        except ImportError:
            missing_modules.append(module)
            print(f"[ERROR] {module} 未安装")
    
    if missing_modules:
        print(f"\n请安装缺失的依赖:")
        print(f"pip install {' '.join(missing_modules)}")
        return False
    
    return True

def check_project_structure():
    """检查项目结构"""
    print_section("项目结构检查")
    
    required_files = [
        "service/ProgressiveDataManager.py",
        "models/brain_state_models.py",
        "controller/brain_wave_controller.py",
        "test/test_progressive_data_manager.py",
        "test/test_performance.py"
    ]
    
    missing_files = []
    
    for file_path in required_files:
        if os.path.exists(file_path):
            print(f"[OK] {file_path}")
        else:
            missing_files.append(file_path)
            print(f"[ERROR] {file_path} 不存在")
    
    if missing_files:
        print(f"\n缺失的文件: {len(missing_files)} 个")
        return False
    
    print(f"\n[OK] 所有必需文件都存在")
    return True

def run_quick_validation():
    """运行快速验证"""
    print_section("快速验证")
    
    try:
        # 尝试导入主要模块
        sys.path.append(os.getcwd())
        from service.ProgressiveDataManager import ProgressiveDataManager
        
        # 创建实例并进行基本测试
        manager = ProgressiveDataManager("validation-test")
        
        # 添加测试数据
        test_data = {
            'delta': 0.1, 'theta': 0.2, 'alpha': 0.3,
            'beta': 0.2, 'gamma': 0.1, 'poor_signal': 20
        }
        manager.add_data_point(test_data)
        
        # 检查基本功能
        if len(manager.data_buffer) == 1:
            print("[OK] 数据添加功能正常")
        else:
            print("[ERROR] 数据添加功能异常")
            return False
        
        progress = manager.get_warmup_progress()
        if 'percentage' in progress and 'status' in progress:
            print("[OK] 预热进度功能正常")
        else:
            print("[ERROR] 预热进度功能异常")
            return False
        
        manager.reset()
        if len(manager.data_buffer) == 0:
            print("[OK] 重置功能正常")
        else:
            print("[ERROR] 重置功能异常")
            return False
        
        print("[OK] 快速验证通过")
        return True
        
    except Exception as e:
        print(f"[ERROR] 快速验证失败: {e}")
        import traceback
        traceback.print_exc()
        return False

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='渐进式数据管理器测试运行器')
    parser.add_argument('--unit', action='store_true', help='只运行单元测试')
    parser.add_argument('--performance', action='store_true', help='只运行性能测试')
    parser.add_argument('--quick', action='store_true', help='快速测试（跳过性能测试）')
    parser.add_argument('--no-deps-check', action='store_true', help='跳过依赖检查')
    
    args = parser.parse_args()
    
    print_header(f"渐进式数据管理器测试 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    # 检查项目结构
    if not check_project_structure():
        print("\n[ERROR] 项目结构检查失败，请确保所有必需文件都存在")
        return 1
    
    # 检查依赖（除非跳过）
    if not args.no_deps_check and not check_dependencies():
        print("\n[ERROR] 依赖检查失败，请安装缺失的依赖")
        return 1
    
    # 运行快速验证
    if not run_quick_validation():
        print("\n[ERROR] 快速验证失败，请检查代码")
        return 1
    
    test_results = []
    start_time = time.time()
    
    # 根据参数运行相应测试
    if args.unit:
        test_results.append(run_unit_tests())
    elif args.performance:
        test_results.append(run_performance_tests())
    elif args.quick:
        test_results.append(run_unit_tests())
    else:
        # 运行所有测试
        test_results.append(run_unit_tests())
        test_results.append(run_performance_tests())
    
    end_time = time.time()
    duration = end_time - start_time
    
    # 总结结果
    print_header("测试总结")
    passed_tests = sum(test_results)
    total_tests = len(test_results)
    
    print(f"测试完成时间: {duration:.2f} 秒")
    print(f"通过测试: {passed_tests}/{total_tests}")
    
    if passed_tests == total_tests:
        print("\n[SUCCESS] 所有测试通过！")
        print("\n[READY] 渐进式数据管理器已准备就绪")
        print("\n下一步:")
        print("1. 启动服务: python controller/brain_wave_controller.py")
        print("2. 打开测试页面: test_progressive_websocket.html")
        print("3. 连接设备并测试渐进式数据推送")
        return 0
    else:
        print("\n[WARNING] 部分测试未通过")
        print("\n请检查失败的测试并修复相关问题")
        return 1

if __name__ == "__main__":
    sys.exit(main())